import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useHotkeys } from 'react-hotkeys-hook';
import { Layout, Dropdown, Menu, Avatar, Space, message, Tag } from 'antd';
import { MenuUnfoldOutlined, MenuFoldOutlined, GlobalOutlined, GithubOutlined } from '@ant-design/icons';
import { useStore } from '@/store';
import { observer } from 'mobx-react-lite';
import './index.scss';
const { Header } = Layout;

function TopHeader() {
  const { collapsedStore } = useStore();
  const navigate = useNavigate();

  const users = JSON.parse(window.sessionStorage.getItem('news'));

  const [tagClassName, setTagClassName] = useState('newsTag'); //tag样式

  // 绑定热键，退出登录
  useHotkeys('ctrl+k, command+k', () => {
    navigate('/login', {
      replace: true,
    });
    window.sessionStorage.removeItem('news');
    message.success('用户已退出！', 2);
  });

  const menu = (
    <Menu
      items={[
        {
          key: '1',
          label: users.role.roleName,
        },
        {
          key: '2',
          danger: true,
          label: '退出登录',
        },
      ]}
      onClick={({ key }) => {
        // 退出登录
        if (key === '2') {
          navigate('/login', {
            replace: true,
          });
          window.sessionStorage.removeItem('news');
          message.success('用户已退出！', 2);
        }
      }}
    />
  );

  // 前往新闻快览
  const toNews = () => {
    setTagClassName('tagActive');
    setTimeout(() => {
      navigate('/news');
    }, 500);
  };

  return (
    <Header
      className='site-layout-background'
      style={{
        padding: 0,
      }}>
      <Space>
        {React.createElement(collapsedStore.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
          className: 'trigger',
          onClick: () => collapsedStore.setCollapsed(),
        })}
        <Tag icon={<GlobalOutlined />} className={tagClassName} onClick={() => toNews()}>
          前往新闻快览
        </Tag>
      </Space>
      <div style={{ float: 'right', marginRight: '20px' }}>
        <Space>
          <span>
            <Space>
              <Tag icon={<GithubOutlined />} className='git-tag'>
                <a
                  href='https://gitee.com/CodeMak1r/global-news-publish-system'
                  target='_blank'
                  rel='nofollow noreferrer'>
                  GitHub
                </a>
              </Tag>
              欢迎 {users.username} 回来
            </Space>
          </span>
          <Dropdown overlay={menu}>
            <Avatar src='https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/495101/media/6C472602-856B-4B9C-A9B4-05263BD8AC7F_1_201_a_1684144354019.jpeg'></Avatar>
          </Dropdown>
        </Space>
      </div>
    </Header>
  );
}
export default observer(TopHeader);
